package com.wen.utils;

import com.wen.entry.Result;
import com.wen.entry.bean.Information;
import com.wen.moudle.Account;
import com.wen.moudle.Managers.InformationManager;
import com.wen.task.AbstractTask;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class MyPanel {
    List<AbstractTask> tasks = new ArrayList<>();


    Account account;
    String name;
    Integer level;

    // 打印面板
    public void printTheme(){
        System.out.println("========呆呆家族脚本工具集========");
        for (int i = 0; i < tasks.size(); i++) {
            System.out.println(String.format("| %d. %s", i, ((AbstractTask)tasks.get(i)).getTitle()));
        }
        System.out.println(String.format("| %d. %s", tasks.size(),"退出账号"));
        System.out.println("==============================");
        System.out.print(String.format("【Lv.%d %s】>>>",level, name));
    }

    public MyPanel(Account account){
        this.account = account;
    }


    // 注册脚本
    public <T> void register(Class<? extends AbstractTask> z){
        try {
            AbstractTask instance = (AbstractTask) z.getConstructor(Account.class).newInstance(account);
            tasks.add(instance);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 问候语
    public void sayHello(){
        InformationManager informationManager = new InformationManager(account);
        Information information = informationManager.getInfo().getData();
        this.name = information.getName();;
        this.level = information.getLevel();;
        System.out.println(String.format("【Lv.%d %s】,欢迎您",level, name));
        log.info("开始签到");
        Result<String> result = informationManager.checkIn();
        log.info("{}",result.isSuccess() ?  result.getData(): result.getErrorMessage());
    }

    public void run(){
        Result<String> result = account.login();
        if (!result.isSuccess())return;

        // 第一次登录
        if (!AccountManager.exist(account)){
            System.out.println("您是第一次登录,是否需要保存账号方便下次登录?[y/n]");
            if (ConsoleUtils.yesOrNo()) {
                AccountManager.saveAccount(account);
            }
        }

        // 问候语
        sayHello();

        try {

            while (true){
                printTheme();
                // 获取选中的功能
                int input = ConsoleUtils.inputNumber(0,tasks.size());
                if (input < tasks.size()){
                    tasks.get(input).run();
                    System.out.println("确认键继续...");
                    ConsoleUtils.enter();
                    continue;
                }
                break;
            }
        }finally {
            account.logout();
        }
    }


}
